<template>
  <div>
    <el-card>
      <el-tabs>
        <el-tab-pane label="角色管理">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            style="margin-top: 30px"
            @click="addRole"
          >
            新建角色
          </el-button>
          <el-table
            v-loading="loading"
            highlight-current-row
            :border="true"
            :data="list"
          >
            <el-table-column type="index" label="序号" width="180">
            </el-table-column>
            <el-table-column prop="name" label="角色名称" width="260">
            </el-table-column>
            <el-table-column prop="description" label="描述"> </el-table-column>
            <el-table-column label="操作" width="260">
              <template slot-scope="{ row }">
                <el-button
                  type="success"
                  size="small"
                  @click="assignPerm(row.id)"
                >
                  分配权限
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  @click="editRole(row.id)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="deleteRole(row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 弹层 -->
          <el-dialog
            :title="showTitle"
            :visible="showDialog"
            @close="closeDialog"
          >
            <el-form
              ref="roleForm"
              label-width="120px"
              :model="roleInfo"
              :rules="rules"
            >
              <el-form-item prop="name" label="角色名称">
                <el-input v-model="roleInfo.name"></el-input>
              </el-form-item>
              <el-form-item label="角色描述">
                <el-input v-model="roleInfo.description"></el-input>
              </el-form-item>
              <el-row type="flex" justify="center">
                <el-col :span="8">
                  <el-button size="small" @click="closeDialog">取消</el-button>
                  <el-button type="primary" size="small" @click="submitForm">
                    确定
                  </el-button>
                </el-col>
              </el-row>
            </el-form>
          </el-dialog>
          <el-row
            type="flex"
            justify="center"
            align="middle"
            style="height: 60px"
          >
            <el-pagination
              layout="prev, pager, next"
              :total="total"
              :page-size="page.pagesize"
              :current-page="page.page"
              @current-change="pageChange"
            >
            </el-pagination>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="公司信息">
          <el-alert
            title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
            type="info"
            show-icon
            :closable="false"
            style="margin-bottom: 30px"
          >
          </el-alert>
          <el-form label-width="100px">
            <el-form-item label="公司名称">
              <el-input
                v-model="companyInfo.name"
                style="width: 400px"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="公司地址">
              <el-input
                v-model="companyInfo.companyAddress"
                style="width: 400px"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="公司电话">
              <el-input
                v-model="companyInfo.companyPhone"
                style="width: 400px"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input
                v-model="companyInfo.mailbox"
                style="width: 400px"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="companyInfo.remarks"
                style="width: 400px"
                disabled
              ></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 点击分配权限 - 显示弹层 -->
    <el-dialog title="分配权限" :visible="showPermDialog" @close="cancelPerm">
      <el-tree
        ref="tree"
        :data="permList"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        :default-checked-keys="permIds"
        :check-strictly="true"
      ></el-tree>
      <!-- 下方按钮 -->
      <el-row type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="small" @click="submitNewPerm">
            确定
          </el-button>
          <el-button size="small" @click="cancelPerm">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoleList,
  getCompanyInfo,
  deleteRole,
  getRoleInfo,
  updateRole,
  addRole
} from '@/api/setting'
import { getPermissionList, assignPerm } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
export default {
  data() {
    return {
      list: [],
      page: {
        page: 1,
        pagesize: 10
      },
      total: 0,
      companyInfo: {},
      roleInfo: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称为必填项', trigger: 'blur' }]
      },
      showDialog: false,
      showPermDialog: false,
      permList: [], // 权限列表数组
      defaultProps: {
        // 树形组件显示的节点名称
        label: 'name',
        children: 'children'
      },
      permIds: [], // 存储角色所拥有的权限id，用于弹窗显示之后的数据回写
      roleId: '',
      loading: false
    }
  },
  computed: {
    showTitle() {
      if (this.roleInfo.id) {
        return '编辑角色'
      } else {
        return '新建角色'
      }
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      this.loading = true
      const result = await getRoleList(this.page)
      // console.log(result)
      this.list = result.rows
      this.total = result.total
      this.loading = false
    },
    // 获取公司详细信息
    async getCompanyInfo() {
      const result = await getCompanyInfo(this.$store.getters.companyId)
      this.companyInfo = result
    },
    // 改变页码
    pageChange(currentPage) {
      this.page.page = currentPage
      this.getRoleList()
    },
    // 删除角色
    async deleteRole(id) {
      try {
        await this.$confirm('确认删除该角色吗？')
        await deleteRole(id)
        console.log(id)
        const res = await this.getRoleList() // 获取列表得到最新的total
        // console.log(res)
        if (res === undefined) {
          this.page.page = Math.floor(this.total / this.page.pagesize) //
          this.pageChange(this.page.page)
        }
      } catch (error) {
        console.log(error)
      }
    },
    async editRole(id) {
      const result = await getRoleInfo(id)
      this.roleInfo = result // 实现数据的回写 - 先回写再显示弹层 - 弹层出来不会有一瞬间的空内容
      this.showDialog = true // 显示弹层
    },
    async submitForm() {
      try {
        await this.$refs.roleForm.validate() // 不传参数（参数为回调函数）时，返回promise对象
        if (this.roleInfo.id) {
          // 如果有id，说明是编辑  -  因为编辑的时候调了获取详细信息的接口，将接口传回来的数据赋值给了roleInfo
          await updateRole(this.roleInfo)
          this.getRoleList()
        } else {
          // 新增业务
          await addRole(this.roleInfo)
          await this.getRoleList()
          this.page.page = Math.ceil(this.total / this.page.pagesize)
          this.pageChange(this.page.page)
        }
        this.showDialog = false
        this.$message.success('操作成功')
      } catch (error) {
        console.log(error)
      }
    },
    closeDialog() {
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    addRole() {
      this.roleInfo = {
        name: '',
        description: ''
      }
      this.showDialog = true
    },
    // 分配权限
    async assignPerm(id) {
      this.roleId = id
      // 获取所有权限列表 - 转化成树形
      this.permList = tranListToTreeData(await getPermissionList(), '0')
      // 获取角色所拥有的权限id - 实现数据回写
      const { permIds } = await getRoleInfo(id)
      this.permIds = permIds
      // 显示弹框
      this.showPermDialog = true
    },
    async submitNewPerm() {
      this.permIds = this.$refs.tree.getCheckedNodes() // el-tree组件上的该方法返回被选中的节点的keys所组成的数组
      // console.log(this.permIds)
      await assignPerm({ id: this.roleId, permIds: this.permIds })
      this.$message.success('分配权限成功')
      this.showPermDialog = false
    },
    cancelPerm() {
      this.showPermDialog = false
      this.permIds = [] // 清空选中的节点
    }
  }
}
</script>

<style></style>
